﻿using CommonTools;
using Flurl.Http;
using shop.Bll;
using shop.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using unvell.ReoGrid;

namespace shop.job
{
    public partial class JobsForm : Form
    {
        private readonly Lazy<IFlurlClient> _client = new Lazy<IFlurlClient>(() => myApp.GetClient());

        public JobsForm()
        {
            InitializeComponent();
        }


        public async void RefreshData(int jobId)
        {
            if (jobId <= 0)
            {
                btnRefresh_Click(null, null);
            }
            else
            {
                // 刷新一条
                this.btnRefresh.Enabled = false;
                this.Cursor = Cursors.WaitCursor;

                try
                {
                    var list = await _client.Value.Request("Jobs/QueryJobs")
                       .AppendQueryParam("user", UserBll.CurrentUser.Name)
                       .AppendQueryParam("jobId", jobId)
                       .GetJsonAsync<List<BackgroundJob>>();

                    if (list.Count > 0)
                    {
                        bool find = false;
                        foreach (DataGridViewRow item in this.xDataGrid1.Rows)
                        {
                            if (item.Tag is BackgroundJob job && job.id == jobId)
                            {
                                var arr = new object[]
                                {
                                list[0].CreateTime,
                                list[0].JobName,
                                list[0].FUser,
                                list[0].JobStatus,
                                list[0].FileLink,
                                };

                                item.SetValues(arr);
                                item.Tag = list[0];
                                find = true;
                                break;
                            }
                        }

                        if(find == false)
                        {
                            this.xDataGrid1.InsertItem(0, list, 
                             a => a.CreateTime,
                             a => a.JobName,
                             a => a.FUser,
                             a => a.JobStatus,
                             a => a.FileLink);
                        }
                    }

                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                    this.btnRefresh.Enabled = true;
                }

            }
        }

        private async void btnRefresh_Click(object sender, EventArgs e)
        {
            this.xDataGrid1.Rows.Clear();
            this.btnRefresh.Enabled = false;
            this.Cursor = Cursors.WaitCursor;

            try
            {
                var list = await _client.Value.Request("Jobs/QueryJobs")
                   .AppendQueryParam("user", UserBll.CurrentUser.Name)
                   .GetJsonAsync<List<BackgroundJob>>();

                this.xDataGrid1.AddItems(list,
                    a => a.CreateTime,
                    a => a.JobName,
                    a => a.FUser,
                    a => a.JobStatus,
                    a => a.FileLink);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                this.Cursor = Cursors.Default;
                this.btnRefresh.Enabled = true;
            }

        }

        private async void btn_test1_Click(object sender, EventArgs e)
        {
            var job = new BackgroundJob()
            {
                JobName = "aaa", 
                FUser = UserBll.CurrentUser.Name, 
                UserId= UserBll.CurrentUser.Code.ToString(),
                CreateTime = DateTime.Now, 
                JobRemarks = "aaaa", 
                FileLink="http://www.baidu.com"
            };

            var res = await _client.Value.Request("Jobs/CreateJob")
              .PostJsonAsync(job)
              .ReceiveString();

            MessageBox.Show(res);
        }



        private async void xDataGrid1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if(e.ColumnIndex<0 || e.RowIndex<0)
            {
                return;
            }

            if(e.ColumnIndex == cl_download.Index)
            {
                //var str = xDataGrid1[cl_filelink.Index, e.RowIndex].Value.IsNull();
                //if(!string.IsNullOrEmpty(str) )
                //{
                //    try
                //    {
                //        Process.Start(str);
                //    }
                //    catch (Exception ex)
                //    {
                //        MessageBox.Show("下载错误\r\n" + ex.Message, Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                //    }
                //}
            }
            else if(e.ColumnIndex == cl_filelink.Index)
            {
                var str = xDataGrid1[cl_filelink.Index, e.RowIndex].Value.IsNull();
                if (!string.IsNullOrEmpty(str))
                {
                    this.Cursor= Cursors.WaitCursor;
                    xDataGrid1[cl_download.Index, e.RowIndex].Value = "正在下载";

                    try
                    {
                        await DownloadFile(str);
                        xDataGrid1[cl_download.Index, e.RowIndex].Value = "下载完成";
                    }
                    catch (Exception ex)
                    {
                        xDataGrid1[cl_download.Index, e.RowIndex].Value = "下载错误";
                        MessageBox.Show("下载错误\r\n" + ex.Message, Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    finally
                    {
                        this.Cursor = Cursors.Default;
                    }
                }
            }

        }


        private async Task DownloadFile(string url )
        {
            var dialog = new SaveFileDialog()
            {
                FileName= Path.GetFileName(url),
                DefaultExt = Path.GetExtension(url),
                AddExtension= true,
            };

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                var fd = await url.DownloadFileAsync(Path.GetDirectoryName(dialog.FileName), Path.GetFileName(dialog.FileName));

                Process.Start(fd);
            }

        }


        private void JobsForm_Shown(object sender, EventArgs e)
        {
            this.btnRefresh.PerformClick();
        }
    }
}
